package com.pms.api;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.pms.controller.BaseController;
import com.pms.exception.R;
import com.pms.exception.RRException;
import com.pms.service.tsdb.IIotDeviceService;
import com.pms.validator.Assert;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * 聚合函数类型{1-求平均数，2-总记录数，3-求总和,4-求相邻值的差,5/6-求最大/小值,7/8-求倍数/除数,9/10-求第一个/最后一个值}
 */
@RestController
@Api(value = "设备接入规则Api接口", description = "设备接入规则Api接口")
@RequestMapping(value = "iotRule", method = RequestMethod.POST)
public class IotRuleApi extends BaseController {
    @Autowired
    IIotDeviceService iotDeviceService;

    @ApiOperation(value = "查询规则详情")
    @RequestMapping(value = "/readRules", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "address", value = "查询地址(1-广州默认，2-北京)", required = false, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "deviceName", value = "设备名称", required = true, dataType = "string", paramType = "form"),
    })
    public R readRules(Integer address,String deviceName) {
        Assert.parameterIsBlank(deviceName, "设备名称不能为空");
        JSONObject dataJson = iotDeviceService.readRules( address,deviceName);
        return R.ok().put("code", dataJson.get("iotHttpCode")).put("data", dataJson);
    }

    @ApiOperation(value = "禁用规则")
    @RequestMapping(value = "/disableRules", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "address", value = "查询地址(1-广州默认，2-北京)", required = false, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "deviceName", value = "设备名称", required = true, dataType = "string", paramType = "form"),
    })
    public R disableRules(Integer address,String deviceName) {
        Assert.parameterIsBlank(deviceName, "设备名称不能为空");
        JSONObject dataJson = iotDeviceService.disableRules(address,deviceName);
        return R.ok().put("code", dataJson.get("iotHttpCode")).put("data", dataJson);
    }

    @ApiOperation(value = "启用规则")
    @RequestMapping(value = "/enableRules", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "address", value = "查询地址(1-广州默认，2-北京)", required = false, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "address", value = "查询地址(1-广州默认，2-北京)", required = false, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "deviceName", value = "设备名称", required = true, dataType = "string", paramType = "form"),
    })
    public R enableRules(Integer address,String deviceName) {
        Assert.parameterIsBlank(deviceName, "设备名称不能为空");
        JSONObject dataJson = iotDeviceService.enableRules(address,deviceName);
        return R.ok().put("code", dataJson.get("iotHttpCode")).put("data", dataJson);
    }

    @ApiOperation(value = "删除规则")
    @RequestMapping(value = "/delRules", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "address", value = "查询地址(1-广州默认，2-北京)", required = false, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "deviceName", value = "设备名称", required = true, dataType = "string", paramType = "form"),
    })
    public R delRules(Integer address,String deviceName) {
        Assert.parameterIsBlank(deviceName, "设备名称不能为空");
        JSONObject dataJson = iotDeviceService.delRules(address,deviceName);
        return R.ok().put("code", dataJson.get("iotHttpCode")).put("data", dataJson);
    }

    @ApiOperation(value = "创建规则,sources参数组建jsonArray对象,eg:{\"sources\": [{\"description\": \"\",\"name\": \"name\",\"type\": \"string\",\"condition\": \"<>\",\"value\": \"bbbbb\"}]}")
    @RequestMapping(value = "/testCreateRules", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "address", value = "查询地址(1-广州默认，2-北京)", required = false, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "deviceName", value = "设备名称", required = true, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "ruleName", value = "规则名称,eg: device xxxx to TSDB yyyy", required = true, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "sourcesDesc", value = "(数据)来源描述,多个以,分开", required = true, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "sourcesName", value = "(数据)来源名称,多个以,分开", required = true, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "sourcesType", value = "(数据)来源类型(1-number,2-string),多个以,分开", required = true, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "sourcesCondition", value = "(数据)来源条件(1-大于,2-大于等于,3-等于,4-不等于,5-小于,6-小于等于,7-*上传所有,8-均不上传),多个以,分开", required = true, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "sourcesValue", value = "(数据)来源值,多个以,分开", required = true, dataType = "string", paramType = "form"),
    })
    public R testCreateRules(Integer address,String deviceName, String ruleName, String sourcesDesc, String sourcesName, String sourcesType, String sourcesCondition, String sourcesValue) {
        if (StringUtils.isBlank(ruleName)) {
            return R.error(400, "规则名称不能为空");
        }
        if (StringUtils.isBlank(sourcesType)) {
            return R.error(400, "(数据)来源类型不能为空");
        }
        if (StringUtils.isBlank(sourcesName)) {
            return R.error(400, "(数据)来源名称不能为空");
        }
        if (StringUtils.isBlank(sourcesCondition)) {
            return R.error(400, "(数据)来源条件不能为空");
        }
        if (StringUtils.isBlank(sourcesValue)) {
            return R.error(400, "(数据)来源值不能为空");
        }
        JSONObject paramJsonObj = new JSONObject();
        String[] sourcesNameArr = sourcesName.split(",");
        String[] sourcesTypeArr = sourcesType.split(",");
        String[] sourcesConditionArr = sourcesCondition.split(",");
        String[] sourcesValueArr = sourcesValue.split(",");
        String[] sourcesDescArr = null;
        JSONArray sourcesArr = new JSONArray();
        if (sourcesNameArr.length == sourcesTypeArr.length
                && sourcesNameArr.length == sourcesConditionArr.length
                && sourcesNameArr.length == sourcesValueArr.length) {
            if (sourcesNameArr.length == 1) {
                JSONObject sourcesObj = new JSONObject();
                sourcesObj.put("name", sourcesNameArr[0]);
                sourcesObj.put("type", convertSourcesType(sourcesTypeArr[0]));
                sourcesObj.put("condition", convertSourcesCondition(sourcesConditionArr[0]));
                sourcesObj.put("value", sourcesValueArr[0]);
                if (StringUtils.isBlank(sourcesDesc)) {
                    sourcesObj.put("description", "");
                }
                if (StringUtils.isNotBlank(sourcesDesc)) {
                    sourcesObj.put("description", sourcesDesc);
                }
                sourcesArr.add(sourcesObj);
            }
            if (sourcesNameArr.length > 1) {
                if (StringUtils.isBlank(sourcesDesc)) {
                    return R.error(400, "((数据)来源描述不能为空");
                }
                sourcesDescArr = sourcesDesc.split(",");
                if (sourcesNameArr.length != sourcesDescArr.length) {
                    return R.error(400, "((数据)来源描述参数格式错误");
                }
                for (int x = 0; x < sourcesNameArr.length; x++) {
                    JSONObject sourcesObj = new JSONObject();
                    sourcesObj.put("name", sourcesNameArr[x]);
                    sourcesObj.put("type", convertSourcesType(sourcesTypeArr[x]));
                    sourcesObj.put("condition", convertSourcesCondition(sourcesConditionArr[x]));
                    sourcesObj.put("value", sourcesValueArr[x]);
                    sourcesObj.put("description", sourcesDescArr[x]);
                    sourcesArr.add(sourcesObj);
                }
            }
        } else {
            return R.error(400, "数据来源参数格式出错");
        }
        paramJsonObj.put("name", ruleName);
        paramJsonObj.put("sources", sourcesArr);//数据上传规则详情
        JSONObject dataJson = iotDeviceService.createRules(address,deviceName, paramJsonObj);
        return R.ok().put("code", dataJson.get("iotHttpCode")).put("data", dataJson);
    }

    @ApiOperation(value = "创建规则,sources参数组建jsonArray对象,eg:{\"sources\": [{\"description\": \"\",\"name\": \"name\",\"type\": \"string\",\"condition\": \"<>\",\"value\": \"bbbbb\"}]}")
    @RequestMapping(value = "/createRules", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "address", value = "查询地址(1-广州默认，2-北京)", required = false, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "deviceName", value = "设备名称", required = true, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "ruleName", value = "规则名称,eg: device xxxx to TSDB yyyy", required = true, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "paramJsonStr", value = "请求参数对象字符串,son对象转换的字符串", required = true, dataType = "string", paramType = "form"),
    })
    public R createRules(Integer address,String deviceName, String paramJsonStr, String ruleName) {
        Assert.parameterIsBlank(deviceName, "设备名称不能为空");
        Assert.parameterIsBlank(ruleName, "规则名称不能为空");
        Assert.parameterIsBlank(paramJsonStr, "请求参数对象字符串不能为空");
        try {
            JSONObject paramJson = JSONObject.parseObject(paramJsonStr);
            if (paramJson.get("sources") == null) {
                return R.error(400, "规则来源sources不能为空");
            }
            paramJson.put("name", ruleName);
            JSONObject dataJson = iotDeviceService.createRules(address,deviceName, paramJson);
            return R.ok().put("code", dataJson.get("iotHttpCode")).put("data", dataJson);
        } catch (JSONException ex) {
            return R.error(400, "参数错误，json解析异常");
        }
    }

    @ApiOperation(value = "修改规则")
    @RequestMapping(value = "/editRules", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "address", value = "查询地址(1-广州默认，2-北京)", required = false, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "deviceName", value = "设备名称", required = true, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "ruleName", value = "规则名称", required = false, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "ruleSourceJsonStr", value = "需要存储的数据的属性和条件,json对象转的字符串,eg:{\"sources\": [{\"description\": \"\",\"name\": \"name\",\"type\": \"string\",\"condition\": \"<>\",\"value\": \"bbbbb\"}]}", required = false, dataType = "string", paramType = "form"),
    })
    public R editRules(Integer address,String deviceName, String ruleName, String ruleSourceJsonStr) {
        Assert.parameterIsBlank(deviceName, "设备名称不能为空");
        JSONObject paramJson = new JSONObject();
        if (StringUtils.isNotBlank(ruleName)) {
            paramJson.put("name", ruleName);
        }
        if (StringUtils.isNotBlank(ruleSourceJsonStr)) {
            try {
                JSONObject ruleSourceJson = JSONObject.parseObject(ruleSourceJsonStr);
                if (ruleSourceJson.get("sources") == null) {
                    return R.error("ruleSourceJsonStr参数出错");
                }
                paramJson.put("sources", ruleSourceJson.get("sources"));
            } catch (JSONException ex) {
                return R.error(400, "参数错误，json解析异常");
            }
        }
        JSONObject dataJson = iotDeviceService.editRules(address,deviceName, paramJson);
        return R.ok().put("code", dataJson.get("iotHttpCode")).put("data", dataJson);
    }


    public String convertSourcesType(String SourcesType) {
        if (SourcesType.equals("1") || SourcesType.equals("number")) {
            return "number";
        } else if (SourcesType.equals("2") || SourcesType.equals("string")) {
            return "string";
        } else {
            throw new RRException("参数sourcesType出错");
        }
    }

    public String convertSourcesCondition(String SourcesCondition) {
        if (SourcesCondition.equals("1") || SourcesCondition.equals(">")) {
            return ">";
        } else if (SourcesCondition.equals("2") || SourcesCondition.equals(">=")) {
            return ">=";
        } else if (SourcesCondition.equals("2") || SourcesCondition.equals(">=")) {
            return ">=";
        } else if (SourcesCondition.equals("3") || SourcesCondition.equals("=")) {
            return "=";
        } else if (SourcesCondition.equals("4") || SourcesCondition.equals("!=")) {
            return "<>";
        } else if (SourcesCondition.equals("5") || SourcesCondition.equals("<")) {
            return "<";
        } else if (SourcesCondition.equals("6") || SourcesCondition.equals("<=")) {
            return "<=";
        } else  if(SourcesCondition.equals("7") || SourcesCondition.equals("*")){
            return "*";
        } else{
            return "";
        }
    }


}
